/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package presentation.view;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import presentation.controller.ControlPanelMyAccount;
import presentation.controller.ControlPanelSeeContacts;
import vo.ContactVO;
import vo.IValueObject;

/**
 *
 * @author Joanna 8a
 */
public class PanelSeeContacts extends javax.swing.JPanel {

    /**
     * Creates new form PanelSeeContacts
     *
     * @param opc 1: ver contactos, 2: Modificar Contactos, 3: Eliminar Contacto
     */
    public PanelSeeContacts(int opc, AuxiliarFrame parent) {
        this.parent = parent;
        initComponents();
        parent.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/presentation/view/images/Contact.png")).getImage());
        if (opc == 1) {
            jButtonUpdateContact.setVisible(false);
            jButtonDeleteContact.setVisible(false);
        } else if (opc == 2) {
            jButtonDeleteContact.setVisible(false);
        } else if (opc == 3) {
            jButtonUpdateContact.setVisible(false);
        }
        
        jTextFieldFindContact.setForeground(Color.GRAY);

        fillTable(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButtonBack = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTableContacts = new javax.swing.JTable();
        jButtonUpdateContact = new javax.swing.JButton();
        jButtonDeleteContact = new javax.swing.JButton();
        jTextFieldFindContact = new javax.swing.JTextField();
        jLabelFind = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Contactos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI Light", 1, 14), new java.awt.Color(0, 102, 102))); // NOI18N

        jButtonBack.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jButtonBack.setText("Volver");
        jButtonBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBackActionPerformed(evt);
            }
        });

        jTableContacts.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nombre", "Apellidos", "Teléfonos", "E-mail"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableContacts.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableContactsMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(jTableContacts);

        jButtonUpdateContact.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jButtonUpdateContact.setText("Modificar Contacto");
        jButtonUpdateContact.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonUpdateContactActionPerformed(evt);
            }
        });

        jButtonDeleteContact.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jButtonDeleteContact.setText("Eliminar Contacto");
        jButtonDeleteContact.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteContactActionPerformed(evt);
            }
        });

        jTextFieldFindContact.setFont(new java.awt.Font("Tahoma", 2, 12)); // NOI18N
        jTextFieldFindContact.setText("Buscar Contacto");
        jTextFieldFindContact.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextFieldFindContactFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldFindContactFocusLost(evt);
            }
        });
        jTextFieldFindContact.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextFieldFindContactKeyReleased(evt);
            }
        });

        jLabelFind.setIcon(new javax.swing.ImageIcon(getClass().getResource("/presentation/view/images/Search.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jButtonUpdateContact)
                        .addGap(27, 27, 27)
                        .addComponent(jButtonDeleteContact)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonBack)
                        .addGap(32, 32, 32))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 453, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabelFind)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldFindContact, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabelFind, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jTextFieldFindContact))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonBack)
                    .addComponent(jButtonUpdateContact)
                    .addComponent(jButtonDeleteContact)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonUpdateContactActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonUpdateContactActionPerformed
        this.setVisible(false);
        String user = new ControlPanelMyAccount().findByIp().getUsername();
        DefaultTableModel mod = (DefaultTableModel) jTableContacts.getModel();
        int row = jTableContacts.getSelectedRow();
        String cont = mod.getValueAt(row, 0).toString() + mod.getValueAt(row, 1).toString();
        parent.cambiarPanel(new PanelUpdateContact(2, user, cont, parent));
    }//GEN-LAST:event_jButtonUpdateContactActionPerformed

    private void jButtonDeleteContactActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteContactActionPerformed
        //1= Para panel eliminar contacto.
        this.setVisible(false);
        String user = new ControlPanelMyAccount().findByIp().getUsername();
        DefaultTableModel mod = (DefaultTableModel) jTableContacts.getModel();
        int row = jTableContacts.getSelectedRow();
        String cont = mod.getValueAt(row, 0).toString() + mod.getValueAt(row, 1).toString();
        parent.cambiarPanel(new PanelUpdateContact(1, user, cont, parent));

    }//GEN-LAST:event_jButtonDeleteContactActionPerformed

    private void jTableContactsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableContactsMouseClicked
        fillComboBox(evt);
    }//GEN-LAST:event_jTableContactsMouseClicked

    private void jButtonBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBackActionPerformed
        parent.dispose();
    }//GEN-LAST:event_jButtonBackActionPerformed

    private void jTextFieldFindContactKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldFindContactKeyReleased
        //if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            fillTable(jTextFieldFindContact.getText());
        //}
    }//GEN-LAST:event_jTextFieldFindContactKeyReleased

    private void jTextFieldFindContactFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldFindContactFocusGained
        if(jTextFieldFindContact.getText().equals("Buscar Contacto")){
            jTextFieldFindContact.setForeground(Color.BLACK);
            jTextFieldFindContact.setFont(new Font("Tahoma", Font.PLAIN, 12));
            jTextFieldFindContact.setText("");
        }
    }//GEN-LAST:event_jTextFieldFindContactFocusGained

    private void jTextFieldFindContactFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldFindContactFocusLost
        if(jTextFieldFindContact.getText().equals("")){
            jTextFieldFindContact.setForeground(Color.GRAY);
            jTextFieldFindContact.setFont(new Font("Tahoma", Font.ITALIC, 12));
            jTextFieldFindContact.setText("Buscar Contacto");
            fillTable(null);
        }
    }//GEN-LAST:event_jTextFieldFindContactFocusLost

    /**
     * Inserta todos los datos de los contactos dentro de la tabla
     * @param name Nombre del contacto
     */
    private void fillTable(String name) {
        String user = new ControlPanelMyAccount().findByIp().getUsername();
        if(name == null){
            name = "";
        }
        List<ContactVO> conta = new ControlPanelSeeContacts().findContacts(user, name);
        insertData(conta);
    }
    
    /**
     * Llena la tabla con los datos necesarios
     * @param con Informacion de los contactos
     */
    private void insertData(List<ContactVO> con){
        DefaultTableModel mod = (DefaultTableModel) jTableContacts.getModel();
        
        int rows = mod.getRowCount();
        
        for(int i = 0; i < rows; i++){
            mod.removeRow(0);
        }

        for (ContactVO ob : con) {
            Object[] row = new Object[4];
            row[0] = ob.getName();
            row[1] = ob.getLastName();
            String phones = new String();
            for (Double phone : ob.getPhones()) {
                phones += phone.longValue() + "  ";
            }
            row[2] = phones;
            row[3] = ((ContactVO) ob).getEmail();
            mod.addRow(row);
        }

        jTableContacts.setModel(mod);
        //jTableContacts.requestFocusInWindow();
    }

    /**
     * Llena el combobox de la tercera celda
     *
     * @param evt Evento del click lanzado por el mouse
     */
    private void fillComboBox(java.awt.event.MouseEvent evt) {
        TableColumn col = jTableContacts.getColumnModel().getColumn(2);
        JComboBox combo = new JComboBox();
        DefaultTableModel mod = (DefaultTableModel) jTableContacts.getModel();
        int row = jTableContacts.rowAtPoint(evt.getPoint());
        List<Double> tel = new ControlPanelSeeContacts().phoneList(new ControlPanelMyAccount().findByIp().getUsername(),
                mod.getValueAt(row, 0).toString() + mod.getValueAt(row, 1));

        for (Double d : tel) {
            combo.addItem(d);
        }

        col.setCellEditor(new DefaultCellEditor(combo));
    }
    private AuxiliarFrame parent;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBack;
    private javax.swing.JButton jButtonDeleteContact;
    private javax.swing.JButton jButtonUpdateContact;
    private javax.swing.JLabel jLabelFind;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTableContacts;
    private javax.swing.JTextField jTextFieldFindContact;
    // End of variables declaration//GEN-END:variables
}
